﻿using System;
using System.Web.Mvc;
using Xoohoo.Extensions;
using Xoohoo.Models.InputModels;

namespace Xoohoo.Modules.Membership.ModelBinders
{
    public class PermissionInputModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var valueProvider = bindingContext.ValueProvider;
            //Guid parentID = !String.IsNullOrEmpty(valueProvider.GetAttemptedValue("parentID"]) ? new Guid(valueProvider.GetAttemptedValue("parentID"]) : Guid.Empty;
            Guid tmpGuid;
            Guid? permissionID = null;
            if (valueProvider.GetAttemptedValue("permissionID").GuidTryParse(out tmpGuid))
                permissionID = tmpGuid;
            Guid? parentID = null;
            if (valueProvider.GetAttemptedValue("parentID").GuidTryParse(out tmpGuid))
                parentID = tmpGuid;

            string moduleName = valueProvider.GetAttemptedValue("moduleName");
            string permissionName = valueProvider.GetAttemptedValue("permissionName");
            return new PermissionInput
            {
                ParentID = parentID,
                PermissionID = permissionID,
                ModuleName = moduleName,
                PermissionName = permissionName
            };  
        }
    }
}
